package org.gl;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.impl.client.DefaultHttpClient;
import org.gl.android.base.R;
import org.gl.utils.AndroidUtil;
import org.gl.utils.DebugUtil;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;

import com.nostra13.example.universalimageloader.UILApplication;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 創建一個MyApplication类，管理打开的应用程序 当程序退出时finish Activity call by：InstantActicity
 * 
 * @author zhaoshuming
 * 
 */
public class GlobalVariable extends Application {
//	file:///sdcard/Universal Image Loader @#&=+-_.,!()~'%20.png", // Image from SD card with encoded symbols
//		"assets://	
	private static List<Activity> activityList = new LinkedList<Activity>();
	private DetectSdcard in;
	private static GlobalVariable instance;
	public static Context applicationContext;
	public final static boolean MltiScreenAble = false;
	public static String Server_IP = "192.168.1.51";
	public static String RESDOWNLOADURL = "http://"+Server_IP+"/JsScript/JsSrcCenter/SrcDown.php";
	public UILApplication mUILApplication;
	/**
	 * 屏幕宽（单位为像素）
	 */
	public static int disPlay_w = 0;
	/**
	 * 屏幕高（单位为像素）
	 */
	public static int disPlay_h = 0;
	/**
	 * 没有外置存储卡则为"cacheDir:/data/data/com.zyfkj.rnbs/files/"否则为："/sdcard/rnbs/"
	 */
	public static String AppFileSystemDir;
	public static DefaultHttpClient DefaultHttpClient;
	public static String URL_image_down="http://hdtv.ap01.aws.af.cm/";

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance = this;
		applicationContext = getApplicationContext();
		Server_IP = AndroidUtil.getServerIPConfig();
		RESDOWNLOADURL = "http://"+Server_IP+"/JsScript/JsSrcCenter/SrcDown.php";
		initFileSystem();
		WindowManager wm = ((WindowManager) applicationContext
				.getSystemService(WINDOW_SERVICE));
		disPlay_h = wm.getDefaultDisplay().getHeight();
		disPlay_w = wm.getDefaultDisplay().getWidth();
		// 注册文件系统变动观察者
		registFileSystemObser();
		mUILApplication = new UILApplication();
		mUILApplication.onCreate();

	}

	/**
	 * /注册文件系统变动观察者
	 */
	private void registFileSystemObser() {
		in = new DetectSdcard();
		IntentFilter intentf = new IntentFilter();
		intentf.addAction(Intent.ACTION_MEDIA_MOUNTED);// 已挂载SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_UNMOUNTED);// 未挂载SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);// 恶意拔SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_SHARED);// 被挂起SDCARD
		intentf.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);// 无法挂载SDCARD
		// 隐式intent需要加上下面这句作匹配，否则接收不到广播
		intentf.addDataScheme("file");
		registerReceiver(in, intentf);
	}
	public static final String AppDir= "rnbs";
	/**
	 * 初始化文件系统
	 */
	public void initFileSystem() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ AppDir
					+ File.separator);
			if (!file.exists()) {
				if (!file.mkdirs()) {
					Log.e(this.getClass().getSimpleName(), "外置文件存储目录创建失败");
					AppFileSystemDir = file.getAbsolutePath() + File.separator;
				} else {
					AppFileSystemDir = file.getAbsolutePath() + File.separator;
				}
				;
			} else {
				AppFileSystemDir = file.getAbsolutePath() + File.separator;
			}
		} else {
			AppFileSystemDir = getFilesDir().getAbsolutePath() + File.separator;
		}
		DebugUtil.println("文件系统当前目录:" + AppFileSystemDir);
		initImageLoader(this);
	}

	/**
	 * 得到一个当前的安全的文件存储目录,防止可能的外置存储器错误，如 sdcard被移除;
	 */
	public String getSafeCacheFileDir() {
		initFileSystem();
		return AppFileSystemDir;
	}

	// 检测sdcard是否在机器中
	public class DetectSdcard extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
				// 挂载的...
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
				// 非挂载...
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(
					Intent.ACTION_MEDIA_BAD_REMOVAL)) {
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(Intent.ACTION_MEDIA_SHARED)) {
				getSafeCacheFileDir();
			} else if (intent.getAction().equals(
					Intent.ACTION_MEDIA_UNMOUNTABLE)) {

				getSafeCacheFileDir();
			}
			DebugUtil.println("文件系统变更通知：" + AppFileSystemDir);
		}

	}

	/**
	 * 单例模式中获取唯一的MyApplication实例
	 * 
	 * @return
	 */
	public static GlobalVariable getInstance() {
		if (null == instance) {
			instance = new GlobalVariable();
		}
		return instance;

	}

	/**
	 * 添加Activity到容器中
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	/**
	 * 遍历所有Activity并finish
	 */
	public void exit() {
		if (in != null) {
			try {
				this.unregisterReceiver(in);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		for (Activity activity : activityList) {
			activity.finish();
		}
		System.exit(0);
	}

	public Activity getActivity(String flag) {
		for (Activity activity : activityList) {
			if (flag.equals(activity.getLocalClassName())) {
				return activity;
			}
		}
		return null;
	}

	public static void sendNetExceprionBoast() {
		Context mcontext = activityList.get(activityList.size());
		if(!AndroidUtil.checkNetwork()){
			AndroidUtil.genDialog(mcontext, applicationContext.getResources().getString(R.string.net_error_info),applicationContext.getResources().getString(R.string.net_error),new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
					applicationContext.startActivity(intent);
				}
			});
		}else{
			AndroidUtil.genDialog(mcontext, applicationContext.getResources().getString(R.string.tips_logout),applicationContext.getResources().getString(R.string.disconnect_server),new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getInstance().exit();
				}
			});
		};
		
	}
	
	/**
	 * 初始化图片加载器
	 * 
	 * @param context
	 */
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		DisplayImageOptions di = new DisplayImageOptions.Builder()
				// .showStubImage(R.drawable.ic_more)
				// .showImageForEmptyUri(R.drawable.ic_error)
				// .showImageOnFail(R.drawable.ic_error)
				.cacheInMemory(true).cacheOnDisc(true)
				.displayer(new RoundedBitmapDisplayer(3)).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.defaultDisplayImageOptions(di)
				// .writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
}
